import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { FormControl, NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslatePipe, TranslateService } from '@ngx-translate/core';
import { ActionSheetComponent, ActionSheetConfig, ActionSheetService, SkinType } from 'ngx-weui';
import { Observable, Subject, timer } from 'rxjs';
import { ObserveOnSubscriber } from 'rxjs/internal/operators/observeOn';
import { map } from 'rxjs/operators';
import { ApiService } from 'src/app/core/api';
import { Global } from 'src/app/core/global';
import { StorageService } from 'src/app/core/sotrage/storage.service';
import { GB } from '../../../environments/environment';
import { I18nService } from '../../core/i18n/i18n.service';
import { UiService } from '../../ui.service';

@Component({
	selector: 'app-index',
	templateUrl: './index.component.html',
	styleUrls: ['../login/index.component.less'],
})
export class RegisterComponent implements OnInit {

	constructor(private i: I18nService, private router: Router, private fb: FormBuilder, private global: Global, private api: ApiService, private sto: StorageService) {
		this.i.get(['register-code', 'register-user']).subscribe(res => {
			this.msgData = res;
		});
		this.userForm = this.fb.group(
			{
				email: [null, [Validators.required, Validators.pattern("^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z-]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]|net|NET|asia|ASIA|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT|cn|CN|cc|CC)$")]],
				imageCode: [null, [Validators.required]],
				loginId: [null, [Validators.required]],
				mobile: [null, [Validators.required]],
				verifyCode: [null, [Validators.required]],
				loginPw: [null, [Validators.required]],
				reLoginPw: [null, [Validators.required]],
			},
			{
				validators: confirmValidator,
			}
		);
		this.passwordForm = this.fb.group({
			loginPw: [null, [Validators.required]],
			reLoginPw: [null, [Validators.required]],
		});

		this.userForm.setErrors({
			email: false,
			mobile: false,
		});
		console.log(this.userForm.controls);
	}
	pageType = 1;

	config: ActionSheetConfig = {
		title: 'Language changes',
	} as ActionSheetConfig;

	gb = GB;
	ob;
	res: any = {
		id: '',
		mail: '',
		mobile: '',
		vcode: '',
		password: '',
		rpassword: '',
		worldpost: '1',
	};
	userForm: FormGroup;
	passwordForm: FormGroup;
	imageVerifyCodeId: any;
	e: number;
	msgData: any;

	sendCodeType = false;
	sendCodeNum = 10;
	_timer;

	ngOnInit() {
		this.api.post('生成图形验证码唯一id', {}).then(res=>{
			this.imageVerifyCodeId = res['data']['imageVerifyCodeId'];
		})
		// this.pageType = this.sto.get('register-type')?this.sto.get('register-type'):1;
	}

	onChangImgCode() {
		this.e = Math.random() * 10000;
	}
	toSendCode() {
		if (this.userForm.value['email']) {
			this.api.post('发送邮箱验证码', { email: this.userForm.value['email'], type: 'reg' }).then(res => {
				this.sendCodeNum = res['data']['count'];
				this.api.msgSuccess(this.msgData['register-code']);
				this.sendCodeType = true;
				this._timer = setInterval(() => {
					if (this.sendCodeNum == 0) {
						this.sendCodeType = false;
						clearInterval(this._timer);
					} else {
						this.sendCodeNum--;
					}
				}, 1000);
			});
		} else {
			this.api.msgEeeor(this.msgData['register-mail-error']);
		}
	}

	onChenkId() {
		this.userForm.value['loginId']
			? this.api.post('检查登录账号是否重复', { loginId: this.userForm.value['loginId'] }).then(res => {
					res['data']['result'] === 'Y' ? this.api.msgEeeor('此账号已注册') : this.api.msgSuccess(res['message']);
			  })
			: null;
	}
	onChenkMail() {
		this.userForm.value['email']
			? this.api.post('检查邮箱是否重复', { email: this.userForm.value['email'] }).then(res => {
					res['data']['result'] === 'Y' ? this.api.msgEeeor('此邮箱已注册') : this.api.msgSuccess(res['message']);
			  })
			: null;
	}

	onSave(f) {
		const data = f.value;
		data['imageVerifyCodeId'] = this.imageVerifyCodeId;
		data.level = 'normal';
		if (data['loginPw'] == data['reLoginPw']) {
			this.api.post('注册', data).then(res => {
				this.sto.set('user', res['data']);
				if (sessionStorage.getItem('returnurl')) {
					const url = sessionStorage.getItem('returnurl');
					sessionStorage.removeItem('returnurl');
					this.router.navigateByUrl(url);
				} else {
					this.router.navigate(['/']);
				}
			});
		} else {
			this.api.msgEeeor('密码不一致');
		}
	}
}

export const confirmValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
	const password = control.get('loginPw');
	const newConfirmPassword = control.get('reLoginPw');
	return password.value !== newConfirmPassword.value ? { newConfirmPasswordError: true } : null;
};
